/*
 * @Author: yuanweijiang
 * @Date: 2025-05-30 17:50:10
 * @LastEditors: yuanweijiang
 */
import uuid from './uuid.js';
let Deferred = {
	_events: Object.create(null),
	init(native) {
		if (native) {
			//混合开发下native模块挂载全局变量
			window.viewer.Deferred = Deferred;
		} else {
			//混合开发下web端初始化websocket通信
			window.viewer = GlobalViewer;
			window.viewer.Deferred = Deferred;
			window.viewer.onNativeNotify((res) => {
				if (res.type == 'invokeMethod') {
					let data = res.data;
					this.emit(data.id, ...data.args);
				}
			});
		}
	},
	add(fn, once = true) {
		let id = uuid();
		if (once) {
			this.once(id, fn);
		} else {
			this._events[id] = fn;
		}
		return id;
	},
	emit(id) {
		let args = this._toArray(arguments, 1);
		try {
			SSmap.notify({
				type: 'invokeMethod',
				data: {
					id: id,
					args: args,
				},
			});
		} catch (error) {
			let cb = this._events[id];
			if (cb) {
				cb(...args);
			}
		}
	},
	once(id, fn) {
		let vm = this;
		function add() {
			let args = vm._toArray(arguments);
			vm.off(id);
			fn(...args);
		}
		this._events[id] = add;
	},
	off(id) {
		if (!arguments.length) {
			this._events = Object.create(null);
			return;
		}
		delete this._events[id];
	},
	_toArray(list, start) {
		start = start || 0;
		let i = list.length - start;
		const ret = new Array(i);
		while (i--) {
			ret[i] = list[i + start];
		}
		return ret;
	},
};

export { Deferred };
